from model import *
import sys

def dump_logs(filename=None):
    query = Log.all()
    histories = {}
    batch = query.fetch(1000)
    while batch:
        for log in batch:
            histories.setdefault(log.string_key, []).append(log)
        batch = query.with_cursor(query.cursor()).fetch(1000)

    file = filename and open(filename, 'w') or sys.stdout
    for key in sorted(histories.keys()):
        for log in sorted(histories[key], key=lambda log: log.updated):
            print >>file, log.updated, log.string_key, log.ip_addr, log.json_value
        print >>file
    filename and file.close()

def dump_items(filename=None):
    query = Item.all().order('updated')
    batch = query.fetch(1000)
    file = filename and open(filename, 'w') or sys.stdout
    while batch:
        for item in batch:
            print >>file, item.updated, item.key().name(), item.json_value
        batch = query.with_cursor(query.cursor()).fetch(1000)
    filename and file.close()
